package com.yc.damai.web;

import com.yc.damai.util.QRCodeUtil;
import com.yc.login.web.UserDo;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;

@ServerEndpoint("/scanLogin/{uuid}")
@RestController
public class QrCodeDo {

    // PC 显示二维码
    @RequestMapping(path = "loginCode",
        produces = MediaType.IMAGE_PNG_VALUE)
    public void loginCode(OutputStream out, HttpServletResponse response) throws Exception {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        Cookie cookie = new Cookie("uuid", uuid);
        cookie.setPath("/");
        response.addCookie(cookie);
        String url = "http://172.26.31.159/damai-user/mobile/scanCode/" + uuid;
        System.out.println("url = " + url);
        QRCodeUtil.encode(url, out);
    }

    // 手机扫描
    @RequestMapping("/mobile/scanCode/{uuid}")
    public ModelAndView scanCode(@PathVariable String uuid,
                                 @CookieValue(required = false) String name,
                                 ModelAndView mav,
                                 HttpSession session){
        session.setAttribute("uuid", uuid);
        if(name == null){
            mav.setViewName("redirect:http://172.26.31.159/damai-user/mobile/login.html");
        } else {
         // session.setAttribute("uuid", uuid);
            mav.setViewName("redirect:http://172.26.31.159/damai-user/mobile/auth.html");
        }
        return mav;
    }

    @Resource
    UserDo userDo;

    // 手机端点击 授权
    @RequestMapping("/mobile/authLogin")
    public String authLogin(@SessionAttribute String uuid,
                          @CookieValue String name,
                          @CookieValue String pwd,
                          HttpSession session) throws IOException {
        Object loginedUser = session.getAttribute("loginedUser");
        if(loginedUser != null){
            // 刚才用户是先登录再跳转的授权页面, 当前处于登录状态
        } else {
            // 检测到cookie.name直接打开授权页面, 当前处于未登录状态
            // 远程调用登录方法
            userDo.login(name, pwd, session);
            loginedUser = session.getAttribute("loginedUser");
        }
        // 通知 PC 端登录成功!
        // TODO 使用 WebScoket 主动发出信息通知PC端登录成功!
        final Session webSocketSession = sessionMap.get(uuid);
        webSocketSession.getUserProperties().put("loginedUser", loginedUser);
        webSocketSession.getBasicRemote().sendText("success");
        return "登录成功!";
    }

    private static Map<String,Session> sessionMap = new Hashtable<>();

    @OnOpen
    public void open(Session session, @PathParam("uuid") String uuid){
        System.out.println("=========open==============" + uuid);
        session.getUserProperties().put("uuid", uuid);
        sessionMap.put(uuid,session);
    }

    @OnClose
    public void close(Session session){
        String uuid = (String) session.getUserProperties().get("uuid");
        sessionMap.remove(uuid);
    }

    // PC端
    @RequestMapping("refreshMyinfo/{uuid}")
    public Object refreshMyinfo(@PathVariable String uuid,
                                HttpSession httpSession){
        final Session wsSession = sessionMap.get(uuid);
        final Object loginedUser = wsSession.getUserProperties().get("loginedUser");
        httpSession.setAttribute("loginedUser", loginedUser);
        return loginedUser;
    }

}
